package com.zhihuiweijian.demo.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.zhihuiweijian.demo.dao.RolePermissionMapper;
import com.zhihuiweijian.demo.dao.UserMapper;
import com.zhihuiweijian.demo.model.RolePermission;
import com.zhihuiweijian.demo.model.User;
import com.zhihuiweijian.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;



@Service
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

    @Autowired
	private RolePermissionMapper rolePermissionMapper;

	@Override
	@Cacheable(cacheNames = "user", key = "#name")
	public User findByUsername(String name) {
		User user = userMapper.selectByUserName(name);
		String password = new BCryptPasswordEncoder().encode(user.getPassword());
		user.setPassword(password);
		return user;
	}

	@Override
	public Set<String> findPermissions(String username) {
		Set<String> permissions = new HashSet<>();
		List<RolePermission> rolePermissions = rolePermissionMapper.selectByRole(username);
		for(int i =0;i<rolePermissions.size();i++){
			permissions.add(rolePermissions.get(i).getPermission());
		}
		return permissions;
	}

	@Override
	public List<User> findAll() {
		return userMapper.selectAll();
	}

	@Override
	public List<String> findRolePermission(String name) {
		return rolePermissionMapper.selectByUsername(name);
	}

	@Override
	@CacheEvict(key = "#id")
	public void deleteByPrimaryKey(Long id) {
		userMapper.deleteByPrimaryKey(id);
	}

	@Override
	public void updateByPrimaryKey(User user) {
		userMapper.updateByPrimaryKey(user);
	}

	@Override
	public void insert(User user) {
		userMapper.insert(user);
	}

	@Override
	@Cacheable(cacheNames = "user", key = "#id")
	public User findByPrimaryKey(Long id) {
		return userMapper.findByPrimaryKey(id);
	}


}
